package com.spica.spicaschool.network.repository

import androidx.annotation.WorkerThread
import com.skydoves.sandwich.map
import com.skydoves.sandwich.onError
import com.skydoves.sandwich.onException
import com.skydoves.sandwich.suspendOnSuccess
import com.skydoves.whatif.whatIfNotNull
import com.spica.spicaschool.network.ErrorResponseMapper
import com.spica.spicaschool.network.SpicaClient
import com.spica.spicaschool.persistence.dao.NewsDao
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.flow.flow
import kotlinx.coroutines.flow.flowOn
import kotlinx.coroutines.flow.onCompletion
import javax.inject.Inject

/**
 * 新闻的Repo层
 */
class NewsRepository @Inject constructor(
    private val newsDao: NewsDao,
    private val spicaClient: SpicaClient
) {

    /**
     * page：页码
     */
    @WorkerThread
    fun fetchNews(
        page: Int,
        onComplete: () -> Unit,
        onError: (String?) -> Unit
    ) = flow {
        val newsList = newsDao.queryAll()
        if (newsList.isNotEmpty()) {
            emit(newsList)
        }
        val response = spicaClient.fetchNews(page = page)
        response.suspendOnSuccess {
            data.whatIfNotNull {
                newsDao.insert(it.data)
                emit(it.data)
            }
        }.onError {
            //服务器错误的回调
            map(ErrorResponseMapper()) {
                onError("[Code: $code]: $msg")
            }
        }.onException {
            //客户端错误
            onError(message)
        }
    }.onCompletion {
        //触发流程结束的回调
        onComplete()
    }//指定运行线程
        .flowOn(Dispatchers.IO)

}